//
//  LocatFileManager.swift
//  AreaMeasureDevice
//
//  Created by iOS on 2021/6/11.
//

import UIKit
import Foundation
import MapKit

struct FileData {
    var pointX:Double = 0
    var pointY:Double = 0
    var latitude:Double = 0
    var longitude:Double = 0
    var valitude:Double = 0
    init(dataArr:[String]) {
        self.pointX = Double(dataArr[0]) ?? 0
        self.pointY = Double(dataArr[1]) ?? 0
        self.longitude = Double(dataArr[2]) ?? 0
        self.latitude = Double(dataArr[3]) ?? 0
        self.valitude = Double(dataArr[4]) ?? 0
    }
}


private let file1 = "202106101644" // area = 662 dis = 92  ios_area = 650.0  D-value: 12
private let file2 = "202106101651" // area = 716 dis = 97.2  ios_area = 707.0  D-value: 9
private let file3 = "202106171534(1)" // area = 676 dis = 92.9  ios_area = 662.5 D-value: 13.5
private let file4 = "202106171536(2)" // area = 695 dis = 97.2  ios_area = 685.5 D-value: 9.5
private let file5 = "202106171538(3)" // area = 697 dis = 93.1  ios_area = 686.5 D-value: 10.5
private let file6 = "202106171540(4)" // area = 692 dis = 92.6   ios_area = 679.5 D-value: 12.5
private let file7 = "202106171542(5)" // area = 713 dis = 92.9    ios_area = 700.0 D-value: 13
private let file8 = "202106171544(6)" // area = 704 dis = 93.6    ios_area = 692.0 D-value: 12
private let file9 = "202106171546(7)" // area = 721 dis = 94.5   ios_area = 706.5  D-value: 14.5
private let file10 = "202106171548(8)" // area = 694 dis = 93.4   ios_area = 683.5  D-value: 10.5
private let file11 = "202106171549(9)" // area = 664 dis = 91.6    ios_area = 653.0  D-value: 11
private let file12 = "202106171552(10)" // area = 695 dis = 92.9    ios_area = 687.0  D-value: 8
private let file13 = "202106171558(11)" // area = 761 dis = 77.1    ios_area = 755.0  D-value: 6
private let file14 = "202106181148(1)" // area = 4576 dis = 266.7    ios_area = 4497.5 D-value: 78.5
//private let file15 = "202106091251(1)"  // area = 456232 dis = 5358.7
//private let file16 = "20210618154905"   // area = 1207705 dis = 5559.6
private let file18 = "202106231050(1)"  // area = 736 dis = 96.0   ios_area = 726.0 D-value: 10
private let file19 = "202106231100(2)"  // area = 711 dis = 95.0    ios_area = 698.0 D-value: 13
private let file17 = "6.22" // utf8 编码

private let file20 = "202106241120(1)"

// 定宽：20m    机载：2m
private let csvfile_01 = "202106301057(16)"
private let csvfile_02 = "202106301039(8)"
private let csvfile_03 = "202106301049(12)"
private let csvfile_04 = "202106301050(13)"
private let csvfile_05 = "202106301045(10)"
private let csvfile_06 = "202106301052(14)"
private let csvfile_07 = "202106301022(1)"
private let csvfile_08 = "202106301034(6)"
private let csvfile_09 = "202106301047(11)"
private let csvfile_10 = "202106301027(3)"
private let csvfile_11 = "202106301054(15)"
private let csvfile_12 = "202106301059(17)"
private let csvfile_13 = "202106301037(7)"
private let csvfile_14 = "202106301024(2)"
private let csvfile_15 = "202106301032(5)"
private let csvfile_16 = "202106301030(4)"
private let csvfile_17 = "202106301043(9)"


class LocatFileManager: NSObject {

    private var path = Bundle.main.path(forResource: csvfile_02, ofType: "csv")
    
    private var fileDataList:[FileData] = []

    private let calcuUtil:CalcuLateAreaUtil = CalcuLateAreaUtil()
    private let pu:Double = 0.017453292519943
    private var isFirst:Bool = true

    private var tracePoints:[MALonLatPoint] = []
    private var smoothPoints:[MALonLatPoint]!

    var coordList:[CLLocationCoordinate2D] = []
    var polyCoordList:[CLLocationCoordinate2D] = []

    var mathArea:Double = 0
    var mathPermater:Double = 0

    let douglas = DouglasPeuckerUtil()

    override init() {
        super.init()
        self.loadCSVfile()
//        self.loadTextFile()
    }

    func loadCSVfile(){
        do {
//            let cfEncoding = CFStringEncodings.GB_2312_80
//            let endcoding = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(cfEncoding.rawValue))
//            let fileGBKContents = try String(contentsOfFile: path!, encoding: String.Encoding(rawValue: endcoding))
//            let List = fileGBKContents.components(separatedBy: "\r\n")

            let fileContents = try String(contentsOfFile: path!, encoding: .windowsCP1251)
            let List = fileContents.components(separatedBy: "\r\n")
            let subList = List[3 ..< List.count-1]
            debugPrint(subList)
            for item in subList {
                let lineList = item.components(separatedBy: ",")
                let model = FileData(dataArr: lineList)
                self.fileDataList.append(model)
            }
            self.filteList(list: subList)
        } catch let error {
            print("GBK格式解析错误", error.localizedDescription)
        }
        self.getCoordList(list: fileDataList)

    }

    private func filteList(list:ArraySlice<String>){
        // 计算轨迹
        list.forEach { (obj) in
            let lineList = obj.components(separatedBy: ",")
            let model = FileData(dataArr: lineList)
            let coor = CLLocationCoordinate2D(latitude: model.latitude, longitude: model.longitude)
            let coordConvert = AMapCoordinateConvert(coor, .GPS)
            if list.count <= 6 {
                self.polyCoordList.append(coordConvert)
            }else{
                douglas.compress(coord: coordConvert)
                self.polyCoordList =  douglas.getSmoothPathPoints()
            }
//            let point = MALonLatPoint()
//            point.lat = coordConvert.latitude
//            point.lon = coordConvert.longitude
//            self.tracePoints.append(point)
//            if self.tracePoints.count < 3{return}
//            let tool = MASmoothPathTool()
//            tool.intensity = 3
//            tool.threshHold = 0.1
//            tool.noiseThreshhold = 10
//            self.smoothPoints = tool.pathOptimize(self.tracePoints)

        }
    }

    private func getCoordList(list:[FileData]){
        // 计算面积
        list.forEach { (data) in
            if isFirst {
                calcuUtil.zero_cosdist = floor(MathTool.add(x: MathTool.multiply(x: cos(MathTool.multiply(x: Double(MathTool.LatAnalysis_Du(lat: data.latitude)), y: pu)), y: 3083), y: 5)/10)
                self.isFirst = false
            }
            let coor = CLLocationCoordinate2D(latitude: data.latitude, longitude: data.longitude)
            coordList.append(coor)
            if coordList.count < 2 {
                return
            }
            self.getArea(coord: coor)
//            self.mathArea = calcuUtil.getArea(coords: coordList) / 2
            self.getPermater()

        }
    }

    func getArea(coord:CLLocationCoordinate2D)  {
        mathArea = calcuUtil.getTriangleArea(start: coordList[0], latestone: coord, latesttwo: coordList[coordList.count-2])/2
//        mathArea = calcuUtil.getArea(coords: coordList)/2
    }

    func getPermater() {
        mathPermater += calcuUtil.measurePerimeter(locatins: self.coordList)
    }

    func loadTextFile(){
        let filePath = Bundle.main.path(forResource: "b5957815c9d61a942aacd84f186da60d", ofType: "txt")
        let url = URL(fileURLWithPath: filePath!)
        do {
            let fileData = try Data(contentsOf: url)
            let str = String(data: fileData, encoding: .utf8)
            let arr = str!.components(separatedBy: "\t")
            let filteArr = arr.filter { (item) -> Bool in
                return item != ""
            }

            var index = 1
            for (num, item) in filteArr.enumerated() {
                if Int(item) == index {
                    let coor = CLLocationCoordinate2D(latitude: Double(filteArr[num+2])!, longitude: Double(filteArr[num+1])!)
                    if isFirst {
                        calcuUtil.zero_cosdist = floor(MathTool.add(x: MathTool.multiply(x: cos(MathTool.multiply(x: Double(MathTool.LatAnalysis_Du(lat: coor.latitude)), y: pu)), y: 3083), y: 5)/10)
                        self.isFirst = false
                    }
                    coordList.append(coor)
                    debugPrint("文件数据",coor)
                    if coordList.count > 2 {
                        self.getArea(coord: coor)
                    }
                    //            self.mathArea = calcuUtil.getArea(coords: coordList) / 2
                    self.getPermater()
                    let coordConvert = AMapCoordinateConvert(coor, .GPS)
                    douglas.compress(coord: coordConvert)
                    self.polyCoordList =  douglas.getSmoothPathPoints()
                    index += 1
                }

            }
        } catch let error {
            print("文件解析错误", error.localizedDescription)
        }



    }

}
